﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{
    public class Database
    { 
        public static string svrName;
        public static string dbName;
        public static bool intergratedMode;
        public static string usrName; 
        public static string pwd;
       
        public static ConfigDTO cf=new ConfigDTO();

        public string connStr;
        
        public static SqlConnection sqlconn;
        public Database()
        {
            
            KetNoiDB(cf);
        }

       
        public void KetNoiDB(ConfigDTO cfDTO)
        {
            cf = cfDTO;
            svrName = cfDTO.SvrName;
            dbName = cfDTO.DbName;
            intergratedMode = cfDTO.IntergratedMode;
            usrName = cfDTO.UsrName;
            pwd = cfDTO.Pwd;
            
            if (intergratedMode == true)
            {
               
                connStr = "server=" + svrName + "; database=" + dbName + "; Integrated Security = True";
            }
            else
            {
                
                connStr = "server=" + svrName + "; uid=" + usrName + "; pwd=" + pwd + " ;database=" + dbName;
            }

           
            
        }

        public SqlConnection getConnection()
        {
            sqlconn = new SqlConnection(connStr);
            return sqlconn;
        }
     
        public DataTable Execute(string strQuery)
        {
            
            SqlDataAdapter da = new SqlDataAdapter(strQuery, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0];
            
        }

        public void ExecuteNonQuery(string strquery)
        {


            SqlCommand sqlcom = new SqlCommand(strquery, sqlconn);

            sqlconn.Open(); //Mở kết nối
            sqlcom.ExecuteNonQuery(); //Thực hiện câu lệnh truy vấn đã cung cấp ở trên
            sqlconn.Close();

        }
        //Kiểm tra xem có thể kết nối được không
        public bool KiemTraSQLConnection()
        {
            try
            {
                sqlconn = new SqlConnection(connStr);
                sqlconn.Open();
            }
            catch
            {
                return false;
            }
            finally
            {
                sqlconn.Close();
            }
            return true;
        }
    }
         
   
}

    

